layui.use(['table', 'admin', 'ax'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;

    /**
     * 货运订单表管理
     */
    var OrderTransport = {
        tableId: "orderTransportTable"
    };

    /**
     * 货运订单明细表管理
     */
    var OrderTransportDetailed = {
        tableId: "orderTransportDetailedTable"
    };

    /**
     * 初始化表格的列
     */
    OrderTransport.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键'},
            {field: 'tstate', sort: true, title: '订单状态',templet: '#tstateTpl', event: 'tstateSign'},
            {field: 'operateName', sort: true, title: '项目'},
            {field: 'customerName', sort: true, title: '客户'},
            {field: 'transportNumber', sort: true, title: '货运订单', style:'color: #2b85e4;font-weight: 600;'},
            {field: 'customerOrder', sort: true, title: '客户单号', style:'color: #2b85e4;font-weight: 600;',width:150},
            {field: 'undertime', sort: true, title: '下单时间'},

            {field: 'setUnit', title: '装货单位'},
            {field: 'setLocation', title: '装货地址'},
            {field: 'setPeople', title: '联系人'},
            {field: 'setTel', title: '联系电话'},
            {field: 'setMentiontime', sort: true, title: '发货日期', style:'font-weight: 600;'},
            {field: 'getUnit', title: '卸货单位', style:'font-weight: 600;'},
            {field: 'getLocation', title: '卸货地址'},

            {field: 'lineName', sort: true, title: '路线名称'},

            {field: 'getPeople', title: '联系人'},
            {field: 'getTel', title: '联系电话'},
            {field: 'getMentiontime', sort: true, title: '到达时间'},
            {field: 'createTime', sort: true, title: '制单时间'},
            {field: 'createName', title: '制单用户'},
            {field: 'submitTime', sort: true, title: '提交时间'},
            {field: 'submitName', title: '提交用户'},
            {fixed: 'right',align: 'center',width: 90, toolbar: '#tableBar', title: '操作'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    OrderTransport.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        table.reload(OrderTransport.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
                 // 搜索按钮点击事件
                 $('#btnSearch').click(function () {
                     OrderTransport.search();
                 });
                 // 导出excel
                 $('#btnExp').click(function () {
                     OrderTransport.exportExcel();
                 });
            }
        });
    };

    /**
     * 导出excel按钮
     */
    OrderTransport.exportExcel = function () {
        var checkRows = table.checkStatus(OrderTransport.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + OrderTransport.tableId,
        url: Feng.ctxPath + '/orderTransport/examinelist',
        page: true,
        limit: 20,
        height: 360,
        cellMinWidth: 100,
        toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        cols: OrderTransport.initColumn()
    });

    /**
     * 点击处理
     * @param data 点击按钮时候的行数据
     */
    OrderTransport.openCannotDlg = function (data) {
        layer.open({
            type: 2,
            title: '货运订单审核',
            area: ['700px', '500px'],
            anim: 5,
            closeBtn: 0,
            content: Feng.ctxPath + '/orderTransport/toaudit?id=' + data.id,
            end: function () {
                table.reload(OrderTransport.tableId);
                transportDetailed(null);
            }
        });
    };
    
    // 批量通过
    OrderTransport.btnVia = function () {
    	var checkStatus = table.checkStatus('orderTransportTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
            	ids.push(data[i].id);
			}
            layer.confirm('是否通过选中订单?', function(index){
            	layer.close(index);
            	var msg;
                $.ajax({
                	url:Feng.ctxPath + "/orderTransport/batchVia?ids="+ids,
                	cache: false,
                	dataType:"json",
                	beforeSend:function(){
                		msg = layer.msg('审核中。。。请耐心等待', {
                			  icon: 16,
                			  shade: [0.2,'#000'], //0.1透明度的白色背景
                			  time: false
                		});
                	},
                	success:function(data){
                    	layer.close(msg); 
                		if (data.success) {
                        	Feng.success("审核成功!");
                            table.reload(OrderTransport.tableId);
                            transportDetailed(null);
						} else {
							if (data.message !=null &&data.message!='') {
			    				var msg2 =  layer.open({
				  					  title: '提示' ,
				  					  content: data.message,
				  					  btn: ['确定'],
				  					  yes: function (){
				  						  	layer.close(msg2);
				  		                    Feng.error("审核失败！");
				  		                  table.reload(OrderTransport.tableId);
				  		                transportDetailed(null);
				  					  }
			    				});     
							} else {
	  		                    Feng.error("审核失败！");
	  		                  table.reload(OrderTransport.tableId);
	  		                transportDetailed(null);
							}
						}
                	},
                	error:function(data){
                    	layer.close(msg); 
                        Feng.error("审核失败！" + data.responseJSON.message)
                        table.reload(OrderTransport.tableId);
                        transportDetailed(null);
                	}
                })
            }); 
		} else {
			layer.alert('请至少选中一条数据');
		}
    };

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        OrderTransport.search();
    });

    // 导出excel
    $('#btnExp').click(function () {
        OrderTransport.exportExcel();
    });
    
    // 批量通过
    $('#btnVia').click(function () {
        OrderTransport.btnVia();
    });

    // 工具条点击事件
    table.on('tool(' + OrderTransport.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'cannot') {
        	OrderTransport.openCannotDlg(data);
        } 
    });
    
    /**
     * 初始化表格的列     明细
     */
    OrderTransportDetailed.initColumn = function () {
        return [[
            {field: 'id', hide: true, title: '主键',fixed: 'left'},
            {field: 'transportNumber', sort: true, title: '托运订单号',width: 120, style:'color: #2b85e4;font-weight: 600;'},
            {field: 'goodsName', sort: true, title: '商品名称', style:'background-color: #dbf1e1;font-weight: 600;',width: 270},
            {field: 'goodsNumber', sort: true, title: '商品编号', totalRowText: '合计：', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'balenum', sort: true, title: '大包数', totalRow: true, style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'num', sort: true, title: '数量', totalRow: true, style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'transportWeight', sort: true, title: '重量', totalRow: true},
            {field: 'transportPutvolume', sort: true, title: '体积', totalRow: true},
            {field: 'unitprice', sort: true, title: '单价'},
            {field: 'transportMoney', sort: true, title: '金额', totalRow: true},
            {field: 'dpacking', title: '商品包装'},
            {field: 'largeclass', title: '商品大类'},
            {field: 'goodstype', title: '商品类别'},
        ]];
    };

    // 单击行事件
    table.on('row(' + OrderTransport.tableId + ')', function (obj) {
        var data = obj.data;
		$('div[lay-id="' + OrderTransport.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
		$('div[lay-id="' + OrderTransport.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
        transportDetailed(data);
    });
    
    function transportDetailed(data){
    	var transportNumber;
    	if (data!=null) {
    		$("#transportNumber").val(data.transportNumber);
    		transportNumber = data.transportNumber;
		} else {
			transportNumber = 'nodata';
		}
        // 渲染商品明细表格
        var tableResult = table.render({
            elem: '#' + OrderTransportDetailed.tableId,
            url: Feng.ctxPath + '/orderTransportDetailed/list?transportNumber=' + transportNumber,
            page: true,
            limit: 20,
            height: 370,
            toolbar: '#toolbarfromDetailed',
            cellMinWidth: 100,
            totalRow: true ,//开启合计行
            cols: OrderTransportDetailed.initColumn()
        });
    };
    
});
